<template>
  <div>
    <el-row :gutter="20" class="p-top">
      <el-col :span="8">
        <div ref="pdfContainer" class="pdf-container" @mousedown="onMouseDown"></div>
      </el-col>
      <el-col :span="16">
<!--        <Viewer class="viewer" :tabindex="2" :ref="markDownRef" :locale="zh" :value="value" :plugins="plugins" ></Viewer>-->
        <Editor class="editos" :plugins="plugins" :tabindex="2" :ref="markDownRef" :locale="zh" :value="value" />
      </el-col>
    </el-row>
    <div class="p-bottom">
      <a style="margin-top: 10px;display: block" :href="pdfUrl" target="_blank" >{{pdfName}}</a>
      <el-pagination
          v-if="total"
          size="small"
          background
          style="margin-top: 15px;"
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          layout="total, prev, pager, next, jumper"
          :total="total"
          class="pdf-page"
      >
      </el-pagination>
      <span>
          快捷键 上一页：shift + a，下一页 shift + d
        </span>
    </div>
  </div>
</template>
<script setup>
  import {onBeforeMount, ref, computed, markRaw, toRefs, reactive, onMounted} from 'vue';
  import { PdfList } from '../utils/list'
  import * as pdfjsLib from "pdfjs-dist";
  import * as workerSrc from "pdfjs-dist/build/pdf.worker.min?url";
  import { PDFDocument } from "pdf-lib";
  import { useRouter, useRoute } from 'vue-router'
  import { Editor, Viewer } from '@bytemd/vue-next'
  import gfm from '@bytemd/plugin-gfm'
  import gemoji from '@bytemd/plugin-gemoji'
  import highlight from '@bytemd/plugin-highlight' // 代码高亮
  import frontmatter from '@bytemd/plugin-frontmatter' // 解析前题
  import mediumZoom from '@bytemd/plugin-medium-zoom' // 缩放图片
  import breaks from '@bytemd/plugin-breaks'
  import math from '@bytemd/plugin-math'
  import zhHans from 'bytemd/locales/zh_Hans.json'

  import "bytemd/dist/index.min.css";
  // import "highlight.js/styles/atom-one-dark.min.css";
  // import 'juejin-markdown-themes/dist/juejin.min.css' // 掘金同款样式
  // 插件
  const pluginsList = [
    gfm(),
    gemoji(),
    highlight(),
    frontmatter(),
    mediumZoom(),
    breaks(),
    math()
  ]

  // 数据初始化
  const state = reactive({
    value: '',
    plugins: markRaw(pluginsList),
    zh: zhHans,
  })
  const { value, plugins, zh, markDownRef } = toRefs(state)


  // 配置 PDF.js worker 的路径
  pdfjsLib.GlobalWorkerOptions.workerSrc = workerSrc.default;
  const CMAP_URL = "/cmaps/";
  const CMAP_PACKED = true;
  const loading = ref(true)
  const pdfContainer = ref(null);

  const route = useRoute() // 路由
  const pdfUrl = ref('');
  const pdfName = ref('')
  const pdfKey = ref('')
  const pdfJson = ref([])
  let currentPage = ref(1);
  let total = ref(0);
  const markdown = ref('')

  let pdfDoc = null;
  let scale = ref(1.0);
  let isDragging = ref(false);
  let startX = ref(0);
  let startY = ref(0);
  let scrollLeft = ref(0);
  let scrollTop = ref(0);
  const scaleFactor = 1.1;

  // 挂载 DOM 之前
  onBeforeMount(() => {
    pdfKey.value = route?.query?.key
    const pdfInfo = PdfList.filter(item => item.url.indexOf(pdfKey.value) > -1)[0]
    pdfUrl.value = pdfInfo.url
    pdfName.value = pdfInfo.name
    pdfInfo.json && getJson(pdfInfo.json)
  })
  onMounted(async () => {
    const loadingTask = pdfjsLib.getDocument({
      url: pdfUrl.value,
      cMapUrl: CMAP_URL,
      cMapPacked: CMAP_PACKED,
    });
    // const loadingTask = pdfjsLib.getDocument(pdfUrl.value);
    pdfDoc = await loadingTask.promise;
    total.value = pdfDoc.numPages;
    loading.value = false
    renderPage(currentPage.value);
    pdfContainer.value.addEventListener('wheel', function(event) {
      event.preventDefault(); // 阻止默认的滚动行为

      if (event.deltaY < 0) {
        // 向前滚动，放大
        if(scale.value <= 3){
          scale.value *= scaleFactor;
        }
      } else {
        // 向后滚动，缩小
        if(scale.value >= 0.8){
          scale.value /= scaleFactor;
        }
      }
      renderPage(currentPage.value);
    }, { passive: false }); // 注意：在某些浏览器中，需要设置为{ passive: false }以允许默认行为
    window.addEventListener('keydown', handleKeydown);
  });


  const handleKeydown = (e) => {
    if(e.key == 'A' && e.shiftKey){
      prevPage()
    }
    if(e.key == 'D' && e.shiftKey){
      nextPage()
    }
  }

  const nextPage = () => {
    if (currentPage.value < total.value) {
      currentPage.value += 1;
      handleCurrentChange(currentPage.value)
    }
  };

  const prevPage = () => {
    if (currentPage.value > 1) {
      currentPage.value -= 1;
      handleCurrentChange(currentPage.value)
    }
  };

  const getJson = (jsonUrl) => {
    fetch(jsonUrl)
      .then(response => {
        if(response.status === 200){
          //json是返回的response提供的一个方法,会把返回的json字符串反序列化成对象,也被包装成一个Promise了
          return response.json();
        }else{
          return {}
        }
      })
      .then(data => {
        // 处理获取的数据
        pdfJson.value = data
        total.value = data.length
        setMarkdown()
        console.log('jsontotal',total.value)
      })

  }

  const renderPage = async (num) => {
    const page = await pdfDoc.getPage(num);
    // const textContent = await page.getTextContent()
    // if(textContent.items.length){
    //   finalText += `${textContent.items.map(item => item.str).join(' ')}\n`;
    // }
    // console.log(finalText)
    const viewport = page.getViewport({ scale: scale.value });
    const canvas = document.createElement("canvas");
    const context = canvas.getContext("2d");
    canvas.height = viewport.height;
    canvas.width = viewport.width;

    const renderContext = {
      canvasContext: context,
      viewport: viewport,
    };
    await page.render(renderContext).promise;
    pdfContainer.value.innerHTML = "";
    pdfContainer.value.appendChild(canvas);
  };
  const handleCurrentChange = (page) => {
    currentPage.value =page
    renderPage(currentPage.value);
    setMarkdown()
  }

  const onMouseDown = (e) => {
    isDragging.value = true;
    startX.value = e.pageX - pdfContainer.value.offsetLeft;
    startY.value = e.pageY - pdfContainer.value.offsetTop;
    scrollLeft.value = pdfContainer.value.scrollLeft;
    scrollTop.value = pdfContainer.value.scrollTop;
    document.addEventListener("mousemove", onMouseMove);
    document.addEventListener("mouseup", onMouseUp);
  };

  const onMouseMove = (e) => {
    if (!isDragging.value) return;
    const x = e.pageX - pdfContainer.value.offsetLeft;
    const y = e.pageY - pdfContainer.value.offsetTop;
    const walkX = x - startX.value;
    const walkY = y - startY.value;
    pdfContainer.value.scrollLeft = scrollLeft.value - walkX;
    pdfContainer.value.scrollTop = scrollTop.value - walkY;
  };

  const onMouseUp = () => {
    isDragging.value = false;
    document.removeEventListener("mousemove", onMouseMove);
    document.removeEventListener("mouseup", onMouseUp);
  };

  const setMarkdown = () => {
    state.value = pdfJson.value[currentPage.value - 1].page_md
  }

</script>

<style scoped>
  .p-top{
    width: 100%;
    height: calc( 100vh - 50px);
    overflow-y: scroll;
  }
  .p-bottom{
    display: flex;
    align-items: end;
    justify-content: space-around;
    font-size: 14px;
  }
  .pdf-wrapper {
    width: 100%;
    height: 100%;
    position: relative;
    display: flex;
    flex-direction: column;
    align-items: center;
  }
  .render-markdown-wrap{
    border-left: 1px solid #dcdfe6;
    padding-left: 5px;
  }

  .pdf-container {
    width: 100%;
    height: 100%;
    display: flex;
    justify-content: space-evenly;
    align-items: baseline;
    overflow: auto;
    cursor: grab;
  }

  .pdf-container:active {
    cursor: grabbing;
  }
  :deep (.editos) {
    height: calc(100vh - 50px);
  }
  :deep(.bytemd){
    height: 100% !important;
  }

</style>
